package com.dykj.fireFighting.web.personnelstructure;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dykj.fireFighting.api.socialUnit.personnelstructure.dto.PersonnelStructureDto;
import com.dykj.fireFighting.api.socialUnit.personnelstructure.entity.PersonnelStructure;
import com.dykj.fireFighting.api.socialUnit.personnelstructure.service.IPersonnelStructureService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.dto.CommonDto;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.common.core.vo.SelectTreeVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;


import javax.validation.Valid;



/**
 * 消防安全-人员架构管理接口
 *
 * @Author zly
 * @Date  2021-06-28 16:00:17
 */
@Slf4j
@Api(value = "消防安全-人员架构管理接口", tags = {"消防安全-人员架构管理接口"})
@RestController
@RequestMapping("/personnelStructure")
public class PersonnelStructureController {

    @DubboReference
    private IPersonnelStructureService personnelStructureService;

    /**
     * 消防安全-人员架构管理列表
     *
     * @return
     */
    @AutoLog(value = "消防安全-人员架构管理-分页列表查询")
    @ApiOperation(value = "消防安全-人员架构管理分页列表", notes = "消防安全-人员架构管理分页列表")
    @GetMapping("/list")
    @RequiresPermissions("personnelstructure/personnelStructure/list")
    public CommonResult<List<PersonnelStructure>> treeGrid(PersonnelStructureDto personnelStructureDto) {
        /*PageVo<PersonnelStructure> page = personnelStructureService.pageList(commonDto);*/
        HashMap<String, Object> params = new HashMap<>(16);
        if(null !=personnelStructureDto){
           params.put("userName",personnelStructureDto.getUserName());
        }
        params.put("unitId",ShiroUtil.getUser().getEnterpriseId().toString());
       List<PersonnelStructure> list=personnelStructureService.selectStructureList(params);
        return CommonResult.success(list);
    }

    @AutoLog(value = "消防安全-人员架构管理-获取当前用户企业信息")
    @ApiOperation(value = "消防安全-获取当前用户企业信息", notes = "消防安全-获取当前用户企业信息")
    @GetMapping("/getUnitInfo")
    public CommonResult getUnitInfo() {

        LoginUserVo user = ShiroUtil.getUser();
        String unitId = user.getEnterpriseId().toString();
        String unitName = user.getEnterpriseName();
        HashMap<String, Object> unitInfo = new HashMap<>(16);
        unitInfo.put("unitId",unitId);
        unitInfo.put("unitName",unitName);
        return CommonResult.success(unitInfo);
    }

    /**
     * 人员架构树形选择
     * @return
     */
    @ApiOperation(value = "人员架构树形选择", notes = "人员架构树形选择")
    @GetMapping("/getPerStrSelectTree")
    public CommonResult<List<SelectTreeVo>> getDeptSelectTree(String id) {
        try {

            List<SelectTreeVo> treeNodeList = Lists.newArrayList();
            HashMap<String, Object> params = new HashMap<>(16);
            params.put("unitId",ShiroUtil.getUser().getEnterpriseId().toString());
            treeNodeList.add(SelectTreeVo.createParent());
            List<PersonnelStructure> preStrList = personnelStructureService.selectStructureList(params);

            if (!preStrList.isEmpty()) {
                for (PersonnelStructure dept: preStrList) {
                 /*   if(null !=id && StringUtils.isNotBlank(id) && !"0".equals(id)){
                        if(dept.getId().equals(id)){
                            continue;
                        }
                    }*/
                    SelectTreeVo selectTreeVo = new SelectTreeVo();
                    selectTreeVo.setId(dept.getId().toString());
                    selectTreeVo.setName(dept.getUserName());
                    selectTreeVo.setParentId(dept.getParentId().toString());
                    treeNodeList.add(selectTreeVo);
                };
            }
            return CommonResult.success(treeNodeList);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("运行异常，请联系管理员");
        }
    }

    /**
     * 获取消防安全-人员架构管理信息
     */
    @AutoLog(value = "消防安全-人员架构管理-获取消防安全-人员架构管理信息")
    @ApiOperation(value = "获取消防安全-人员架构管理信息", notes = "获取消防安全-人员架构管理信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{id}")
    @RequiresPermissions("personnelstructure/personnelStructure/info")
    public CommonResult<PersonnelStructure> info(@PathVariable("id") String id){
        PersonnelStructure personnelStructure = personnelStructureService.getById(id);
        return CommonResult.success(personnelStructure);
    }

    /**
     * 保存消防安全-人员架构管理信息
     */
    @AutoLog(value = "消防安全-人员架构管理-保存消防安全-人员架构管理信息")
    @ApiOperation(value = "保存消防安全-人员架构管理信息", notes = "保存消防安全-人员架构管理信息")
    @PostMapping("/save")
    @RequiresPermissions("personnelstructure/personnelStructure/save")
    public CommonResult save(@Valid @RequestBody PersonnelStructure personnelStructure) {
        try {
            String userId = Long.toString(ShiroUtil.getUser().getId());
                personnelStructure.setCreateTime(new Date());
                personnelStructure.setCreateBy(userId);

            personnelStructureService.save(personnelStructure);
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 修改消防安全-人员架构管理信息
     */
    @AutoLog(value = "消防安全-人员架构管理-修改消防安全-人员架构管理信息")
    @ApiOperation(value = "修改消防安全-人员架构管理信息", notes = "修改消防安全-人员架构管理信息")
    @PostMapping("/update")
    @RequiresPermissions("personnelstructure/personnelStructure/update")
    public CommonResult update(@Valid @RequestBody PersonnelStructure personnelStructure) {
        try {
            String userId = Long.toString(ShiroUtil.getUser().getId());
            personnelStructure.setUpdateTime(new Date());
            personnelStructure.setUpdateBy(userId);
                personnelStructureService.updateById(personnelStructure);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 删除消防安全-人员架构管理信息
     */
    @AutoLog(value = "消防安全-人员架构管理-删除消防安全-人员架构管理信息")
    @ApiOperation(value = "删除消防安全-人员架构管理信息", notes = "删除消防安全-人员架构管理信息")
    @ApiImplicitParam(paramType = "query", name = "ids", value = "ID数组", dataType = "String", required = true, allowMultiple = true)
    @PostMapping("/delete/{id}")
    @RequiresPermissions("personnelstructure/personnelStructure/delete")
    public CommonResult delete(@PathVariable("id") String id) {
        try {
             List<PersonnelStructure> childList=personnelStructureService.selectListByParentId(id);
             if(childList.size()>0){
               return CommonResult.failed("请先删除下级");
             }
           int count=personnelStructureService.delete(id);
             if(count ==1){
                 return CommonResult.success("删除成功");
             }else {
                 return CommonResult.failed("删除失败，请联系管理员");
             }

        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("删除失败，请联系管理员");
        }
    }


}
